import { OnInit, ViewChild, Component } from '@angular/core';
import { NestedTreeControl } from '@angular/cdk/tree';
import { of, BehaviorSubject } from 'rxjs';
import { delay } from 'rxjs/operators';

/**
 * @title Tree Lazy Load
 */
@Component({
  templateUrl: './tree-lazy-load.component.html',
  styleUrls: ['./tree-lazy-load.component.css'],
})
export class TreeLazyLoadComponent implements OnInit {
  @ViewChild('treelazyLoad', { static: true }) treelazyLoad;

  dataLazySubject = new BehaviorSubject([]);
  treeLazyControl: NestedTreeControl<any>;

  constructor() {
    this.treeLazyControl = new NestedTreeControl(this._getChildren);
  }

  ngOnInit() {
    setTimeout(() => {
      this.dataLazySubject.next([
        {
          name: 'domain lazy',
          workspaces: new BehaviorSubject([]),
        },
      ]);
    });
  }

  hasChildren(node: any) {
    return !!this._getChildren(node);
  }

  onChildToggle(level: number, node: any) {
    if (this.treeLazyControl.isExpanded(node)) {
      switch (level) {
        case 0:
          of([
            {
              name: 'workspace lazy',
              workflows: new BehaviorSubject([]),
            },
          ]).pipe(
            delay(500),
          ).subscribe((data) => {
            node.workspaces.next(data);
            this.treelazyLoad.selectControl.refreshSelectState(node);
          });
          break;
        case 1:
          of([
            {
              workflowName: 'workflow lazy 1',
            },
            {
              workflowName: 'workflow lazy 2',
            },
          ]).pipe(
            delay(500),
          ).subscribe((data) => {
            node.workflows.next(data);
            this.treelazyLoad.selectControl.refreshSelectState(node);
          });
          break;
        default:
          return;
      }
    }
  }

  private _getChildren(node: any) {
    return node.workspaces || node.workflows;
  }
}
